package com.zt.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zt.api.UserInfoFeign;
import com.zt.feign.UserFeign;
import com.zt.service.CardBindingService;
import com.zt.system.CardBinding;
import com.zt.system.Loan;
import com.zt.service.LoanService;
import com.zt.mapper.LoanMapper;
import com.zt.user.UserInfo;
import com.zt.utils.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
* @author 不.凌
* @description 针对表【loan】的数据库操作Service实现
* @createDate 2024-09-03 17:43:57
*/
@Service
public class LoanServiceImpl extends ServiceImpl<LoanMapper, Loan>
    implements LoanService{
    @Resource
    private UserInfoFeign userInfoFeign;
    @Resource
    private UserFeign userFeign;
    @Resource
    private CardBindingService cardBindingService;
    @Override
    public List<Loan> loanFindByUserId() {
        UserInfo userInfoUserId = userInfoFeign.getUserInfoUserId();
        List<Loan> list = this.list(Wrappers.<Loan>lambdaQuery()
                .eq(userInfoUserId.getUserId() != null, Loan::getUserId, userInfoUserId.getUserId()));
        for (Loan loan : list) {
            UserInfo userInfoById = userFeign.getUserInfoById(loan.getUserId());
            loan.setUserInfo(userInfoById);
        }
        return list;
    }

    @Override
    public Result loanByLoanId(Integer loanId) {
        Loan one = this.getOne(Wrappers.<Loan>lambdaQuery()
                .eq(loanId != null, Loan::getLoanId, loanId));
        UserInfo userInfoById = userFeign.getUserInfoById(one.getUserId());
        one.setUserInfo(userInfoById);
        System.out.println("根据还款的id查询到信息"+one);
        return Result.success(one);
    }

    @Override
    @Transactional
    public Result loanUpdate(Loan loan) {
        System.out.println(loan);
        UserInfo userInfoUserId = userInfoFeign.getUserInfoUserId();
        Loan l = new Loan();
        l.setLoanId(loan.getLoanId());
        l.setUserId(userInfoUserId.getUserId());
        l.setLoanAmount(new BigDecimal(0));
        l.setInterestRate(new BigDecimal(0));
        l.setLoanStatus(1);
        l.setLoanType(loan.getLoanType());
        l.setCardNumber(loan.getCardNumber());
        boolean b = this.updateById(l);
        CardBinding one = cardBindingService.getOne(Wrappers.<CardBinding>lambdaQuery()
                .eq(loan.getCardNumber() != null, CardBinding::getCardNumber, loan.getCardNumber()));
        int i = loan.getTotalAmount().intValue();
        one.setBalance(one.getBalance()-i);
        cardBindingService.updateById(one);
        return b?Result.success("成功"):Result.error("失败");
    }
}




